const express = require('express');
const router = express.Router();
const linkController = require('../controllers/link');
const rateLimitMiddleware = require('../controllers/rateLimit');


// 创建短链接
router.post('/v1/links', rateLimitMiddleware("create"), async (req, res) => {
  try {
    const { url } = req.body;
    console.log("请求体：", url)

    if (!url || !isValidUrl(url)) {
      return res.status(400).json({ error: 'URL格式无效' });
    }
    const shortCode = await linkController.createShortLink(url, req);
    console.log("shortCode::", shortCode)
    const shortUrl = `${req.protocol}://${req.get('host')}/${shortCode}`;

    res.status(201).json({
      short_code: shortCode,
      short_url: shortUrl
    });
  } catch (error) {
    console.error('创建短链接时出错：', error);
    res.status(500).json({ error: '内部服务器错误' });
  }
}
);

// 重定向短链接
router.get('/:shortCode', async (req, res) => {
  try {
    const { shortCode } = req.params;
    const originalUrl = await linkController.getOriginalUrl(shortCode);

    if (!originalUrl) {
      return res.status(404).send('未找到短链接');
    }

    // 更新点击计数
    await linkController.incrementClickCount(shortCode);

    // 302临时重定向
    res.redirect(302, originalUrl);
  } catch (error) {
    console.error('重定向时出错：', error);
    res.status(500).send('内部服务器错误');
  }
});

// URL验证函数
function isValidUrl(url) {
  try {
    new URL(url);
    return true;
  } catch (err) {
    return false;
  }
}

module.exports = router;